// 封装互斥量，配合抢票系统使用

// 防止头文件被多次包含
#pragma once

#include <iostream>  // 标准输入输出 (此处主要为 potential error reporting)
#include <string>    // 字符串类 (此处未使用)
#include <pthread.h> // POSIX threads 库，提供 pthread_mutex_t 等互斥量相关功能
#include <cstdio>    // 用于 perror 打印错误信息
namespace LockModule
{
    class Mutex
    {
    public:
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;
        Mutex()
        {
            int n = pthread_mutex_init(&_mutex, nullptr);
            if (n != 0) // 非0表示失败
            {
                perror("pthread_mutex_init failed");
            }
            (void)n;
        }
        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                perror("pthread_mutex_lock failed");
            }
            (void)n;
        }
        void Unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                perror("pthread_mutex_unlock failed");
            }
            (void)n;
        }
        pthread_mutex_t *GetMutexOriginal()
        {
            return &_mutex;
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                perror("pthread_mutex_destroy failed");
            }
            (void)n;
        }

    private:
        pthread_mutex_t _mutex;
    };

    class LockGuard
    {
    public:
        LockGuard(Mutex &mutex) : _mutex(mutex)
        {
            _mutex.Lock();
        }
        ~LockGuard()
        {
            _mutex.Unlock();
        }
        LockGuard(const LockGuard &) = delete;
        const LockGuard &operator=(const LockGuard &) = delete;

    private:
        Mutex &_mutex;
    };
}